package com.education.teacher.shiro;

import com.education.teacher.redis.RedisManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.CacheManager;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;


/**
 * Created by lzh on 2017/8/16.
 * Cache管理类
 * 理解此类实际为一个对象池，shrio实际操作是此对象池返回cache对象
 * 此类必须保持单例
 */
public class ShareCacheManager implements CacheManager {

    /**
     * 线程安全的map
     * 用于做池
     */
    private final ConcurrentMap<String, Cache> caches = new ConcurrentHashMap<>();

    private Logger logger= LogManager.getLogger(ShareCacheManager.class);

    /**
     * 传入Cache对象中用
     */
    private RedisManager redisManager;

    @Override
    public <K, V> Cache<K, V> getCache(String name) throws CacheException {

        logger.info("获取name为 ["+name+"] 的cache对象");

        Cache sc=caches.get(name);//从当前池中获取Cache对象
        if (sc==null){  //当前池中没有，就新建一个Cache对象
            sc=new ShareCache<>(redisManager);
            caches.put(name,sc); //新建之后加入到池中
            logger.info("新建name为 ["+name+"] 的cache对象");
        }
        return sc;
    }

    public void setRedisManager(RedisManager redisManager) {
        this.redisManager = redisManager;
    }
}
